package cn.stacey.day10;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

import org.junit.Test;

public class DemoRandomAccessFile {
@Test
	public void test() {
		String source = "D:\\视频\\day10\\图片\\1.jpg";
		String target="D:\\视频\\day10\\图片\\1111.jpg";
		copy(source,target);
		System.out.println();

		
	}

@Test
	public void remainTest() {
		String source = "D:\\视频\\day10\\图片\\1.jpg";
		String target="D:\\视频\\day10\\图片\\1111.jpg";
		File targetFile=new File(target);
		try(
				RandomAccessFile raf=new RandomAccessFile(source,"r");
				FileOutputStream fo=new FileOutputStream(target,true);
				) {
			long size=targetFile.length();
			raf.seek(size);    //移动文件指针到size大小
			
			byte[] content1=new byte[1024];
			int count1=0;
			while((count1=raf.read(content1))!=-1) {
				fo.write(content1, 0, count1);
			}

			

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		
	}

	public void copy(String source,String target) {
		
		try(	
				FileInputStream fi=new FileInputStream(source);
				FileOutputStream fo=new FileOutputStream(target);
				

				) {
			//为何不重新new一个file把source放进去,它的size就打印为20？？
			System.out.println(source.length());
			File source1=new File(source);
			long size=source1.length();
			System.out.println("原图片的大小为："+size);
			long ran=(long) (Math.random()*size);
			System.out.println("随机图片的大小为："+ran);
			byte[] content=new byte[1024];  //一个字节
			long sum=0;
			int count=0;
			while((count=fi.read(content))!=-1) {
//			while ((count = fi.read(bytes)) != -1)	
				sum+=count;      //每次读一次sum会+1024
//				System.out.println("count值"+count);   //count的值每一次为1024
				System.out.println(sum);
				if(sum>=ran) {
					break;
				}
//				System.out.println("count值"+count);
				fo.write(content,0 ,count );         //理解这里的为何要放count???   
			}
			


		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 

		
		
		
		
	}
}
